dataKey = 'qq_qqlgin'

getTrHtml = (qq='',ps='')->
	"""
		<tr>
			<td>
				<input name="qq[]" type="text" value="#{qq}" placeholder="输入QQ号" />
			</td>
			<td class="passCol">
				<input name="password[]" type="password" value="#{ps}" placeholder="输入QQ密码" />
			</td>
			<td>
				<button type="button" class="btn">登录</button>
			</td>
		</tr>
	"""
editModel = ->
	$('table').addClass('editModel')
	$('input').removeAttr('readonly')

saveUserData = ->
	obj = {}
	obj[dataKey] = $('form').serializeObject()
	chrome.storage.local.set obj

showUserData = (callback)->
	chrome.storage.local.get(dataKey,(item)->
		obj=
			qq:['']
			password:['']
		if item and item[dataKey]
			obj = item[dataKey]
		tbody=''
		for v,i in obj.qq
			if tbody and !v
				continue
			tbody += getTrHtml v,obj.password[i]
		$('tbody').html tbody
		callback()
	)

listen = (data)->
	index = 0
	chrome.extension.onRequest.addListener( (request, sender, sendResponse)->
		if request?.qq
			if request.qq.login
				while on
					unless $("[name='qq[]']")[index]
						alert '完成任务'
						break
					num = $("[name='qq[]']")[index]?.value
					password = $("[name='qq[]']")[index]?.value
					if num and password
						sendResponse qq:{qq:num,password:password}
						break
					index++
			else if request.qq.next
				sendResponse qq:{next:on}
	)	

	

showUserData ->
	$('#save').click saveUserData
	$('#addLine').click ->
		$('tbody').append $(getTrHtml())
		editModel()
	$('#edit').click editModel
	$('form').submit ->
		saveUserData()
		listen()
		open 'https://mail.qq.com/cgi-bin/loginpage'
		false

